package xyz.xxpc.springcloud.consumer.rule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;

public class MyRule extends AbstractLoadBalancerRule {
    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {

    }

    @Override
    public Server choose(Object key) {
        ILoadBalancer lb = getLoadBalancer();
        List<Server> allServers = lb.getAllServers();// 获取到所有的服务
        List<Server> reachableServers = lb.getReachableServers(); // 获取可用的服务
        // 自己实现的算法
        if(reachableServers.size() == 0 || allServers.size() == 0 ){
            System.out.println("没有可用的实例");
            return null;
        }
        Server s = allServers.get(0);
        if(s.isAlive()){
            System.out.println("第1个挂了");
            return s;
        }
        s = allServers.get(1);
        if(s.isAlive()){
            System.out.println("第2个挂了");
            return s;
        }
        Thread.yield();
        return s;
    }
}
